<template>
  <div class="city">
    <Header title="城市选择"></Header>
    <main id="main">
      <van-index-bar :sticky="false" :index-list="az">
        <div v-for="(v,i) in cityList" :key="i">
          <van-index-anchor :index="v.title" />
          <van-cell v-for="(item,index) in v.children" :key="index" :title="item.label" @click="goHome(item.label)" />
        </div>
      </van-index-bar>
      <van-loading color="#1989fa" :vertical="true" size="24px">加载中...</van-loading>
    </main>
  </div>
</template>

<script>
import Header from "../../components/Header";
export default {
  components: {
    Header
  },
  data() {
    return {
      cityList: [],
      cityHotList: [],
      az: []
    };
  },
  methods:{
    goHome(e){
     window.localStorage.setItem('cityName',e)
     this.$router.push('/')
    }
  },
  async created() {
    let city = await this.$http.getCityList();
    let cityHot = await this.$http.getHotCity();
    let city2 = [...city.data.body]; //过滤出来a-z用的
    let A_Z = city2.map(v => {
      return v.short.slice(0, 1).toUpperCase();
    });
    let set = [...new Set(A_Z)];
    let a_z = set.sort(); //首字母组成的数组
    let indexList = [...a_z];
    indexList.unshift("热");
    indexList.unshift("#");
    this.az = indexList;
    a_z.forEach((v, i) => {
      let arr = city.data.body.filter(item => {
        return item.short.slice(0, 1).toUpperCase() === v;
      });
      a_z[i] = {
        title: v,
        children: [...arr]
      };
    });
     a_z.unshift({
      title: "热",
      children:cityHot.data.body
    });
    a_z.unshift({
      title: "#",
      children: [{ label: window.localStorage.getItem("cityName") }]
    });
    this.cityList = a_z;
  }
};
</script>

<style lang='scss'>
.city {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  main {
    flex: 1;
    overflow: auto;
  }
}
.van-cell {
  font-size: 18px;
  line-height: 28px;
}
.city .van-index-bar__sidebar span {
  font-size: 14px !important;
  line-height: 20px;
  font-weight: normal;
}
</style>